package com.jiaolong.interceptor;

import com.jiaolong.utils.RedirectUtil;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用于拦截聚合支付的扫码请求，判断用户使用的是微信支付还是支付宝支付，再组装请求地址请求到对应的Controller
 */
@Component
public class WayInterceptor implements HandlerInterceptor {

    /**
     *  前置拦截，如果返回false，后面的Interceptor和Controller都不会执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpServletResponseWrapper httpResponse = new HttpServletResponseWrapper((HttpServletResponse) response);
        /*
        String targetUrl = determineTargetUrl(request);
        if(null != targetUrl) {
            // 使用RequestDispatcher进行转发
            RequestDispatcher dispatcher = request.getRequestDispatcher(targetUrl);
            dispatcher.forward(request, response);
            return false;
        } else {
            // 在前端中自定义一个错误页面，重定向到该页面
            RedirectUtil.httpRedirect(response, "http://baidu.com");
            return false;
        }

         */
        return true;
    }

    /**
     * 确定请求的目标url：如果是支付宝扫码，则应该请求到支付宝的扫码Controller，微信扫码同理
     * @param request
     * @return
     */
    private String determineTargetUrl(HttpServletRequest request) {

        // 获取请求UA
        String userAgent = request.getHeader("user-agent");

        // 根据扫码客户端确定扫码url
        if(null != userAgent && userAgent.contains("AlipayClient")) {
            return "/api/alipay/payScanCode"; // 注意使用forward:前缀
        }

        // 否则返回null或保持原样
        return null;
    }

}
